package com.openlogic.common.plugins.db.api.plugin;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.openlogic.common.plugins.spi.datasource.DataSourceChannel;
import com.openlogic.common.plugins.spi.datasource.DataSourceChannelFactory;
import com.openlogic.common.plugins.spi.plugin.PrioritySPIFactory;

/**
* @ClassName: DataSourcePluginManager
* @Description: 数据源插件管理器
* @author weiyongpeng
* @date 2024年11月16日 上午8:29:04
 */
public class DataSourcePluginManager {

	private static final Logger log = LoggerFactory.getLogger(DataSourcePluginManager.class);

	private final Map<String, DataSourceChannel> datasourceChannelMap = new ConcurrentHashMap<>();

	public Map<String, DataSourceChannel> getDataSourceChannelMap() {
		return Collections.unmodifiableMap(datasourceChannelMap);
	}

	public void installPlugin() {

		PrioritySPIFactory<DataSourceChannelFactory> prioritySPIFactory = new PrioritySPIFactory<>(
				DataSourceChannelFactory.class);
		for (Map.Entry<String, DataSourceChannelFactory> entry : prioritySPIFactory.getSPIMap().entrySet()) {
			final DataSourceChannelFactory factory = entry.getValue();
			final String name = entry.getKey();

			log.info("Registering datasource plugin: {}", name);

			if (datasourceChannelMap.containsKey(name)) {
				throw new IllegalStateException(String.format("Duplicate datasource plugins named '%s'", name));
			}

			loadDatasourceClient(factory);

			log.info("Registered datasource plugin: {}", name);
		}
	}

	private void loadDatasourceClient(DataSourceChannelFactory datasourceChannelFactory) {
		DataSourceChannel datasourceChannel = datasourceChannelFactory.create();
		datasourceChannelMap.put(datasourceChannelFactory.getName(), datasourceChannel);
	}
}
